from rest_framework.viewsets import GenericViewSet, ViewSet
from rest_framework.decorators import action
from utils.my_drf.response import APIResponse
from django.conf import settings
from django.core.cache import cache
from . import models
from utils.my_drf.admin_auth import AdminJwtAuth, AdminPermission
from record.models import AdminRecord
import json


class ConfigInfoView(ViewSet):
    @action(methods=['get'], detail=False)
    def site(self, request):
        site = self._get_val('site_info', 1)
        return APIResponse(data=site)

    @action(methods=['get'], detail=False)
    def seo(self, request):
        seo = self._get_val('seo_info', 2)
        return APIResponse(data=seo)

    def _get_val(self, cache_name, pk):
        res = cache.get(cache_name)
        if not res:
            obj = models.Config.objects.filter(pk=pk).first()
            res = obj.val
            res = json.loads(res)
            cache.set(cache_name, res, settings.ZEUS_CACHES_TIME)
        return res


class ConfigSetView(GenericViewSet):
    authentication_classes = [AdminJwtAuth, ]
    permission_classes = [AdminPermission, ]

    queryset = models.Config.objects

    @action(methods=['post'], detail=False)
    def site(self, request, *args, **kwargs):
        data = {
            'name': request.data.get('name'),
            'state': request.data.get('state'),
            'stop_info': request.data.get('stop_info')
        }
        val = json.dumps(data, ensure_ascii=False)
        obj = self.get_queryset().filter(pk=1).first()
        obj.val = val
        obj.save()
        AdminRecord.objects.create(group=1, detail='修改站点配置，内容：{}'.format(val),
                                   admin_id=request.user.get('id'))
        cache.delete('site_info')
        return APIResponse(code=202, data=data)

    @action(methods=['post'], detail=False)
    def seo(self, request, *args, **kwargs):
        data = {
            'title': request.data.get('title'),
            'logo': request.data.get('logo'),
            'keywords': request.data.get('keywords'),
            'description': request.data.get('description')
        }
        val = json.dumps(data, ensure_ascii=False)
        obj = self.get_queryset().filter(pk=2).first()
        obj.val = val
        obj.save()
        AdminRecord.objects.create(group=1, detail='修改SEO配置，内容：{}'.format(val),
                                   admin_id=request.user.get('id'))
        cache.delete('seo_info')
        return APIResponse(code=202, data=data)
